// src/main/java/top/csh215/cmd2/controller/AuthController.java
package top.csh215.cmd2.controller;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import top.csh215.cmd2.common.Result;
import top.csh215.cmd2.dto.LoginDto;
import top.csh215.cmd2.entity.Permission;
import top.csh215.cmd2.entity.Role;
import top.csh215.cmd2.entity.User;
import top.csh215.cmd2.service.UserService;
import top.csh215.cmd2.vo.LoginVo;
import top.csh215.cmd2.vo.UserInfoVo;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     * @param loginDto 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto) {

        // 验证用户，“1”代表 禁用 或者 删除
        User user = userService.getByUsername(loginDto.getUsername());
        if (user == null || "1".equals(user.getStatus()) || "1".equals(user.getIsDelete())){
            return Result.error("用户不存在或已被禁用");
        }

        // 验证密码
        if (!userService.login(loginDto.getUsername(), loginDto.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 登录授权，使用 Sa-Token 获取token
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();

        // 构造用户信息
        UserInfoVo userInfoVo = buildUserInfo(user);

        LoginVo loginVo = new LoginVo(token, userInfoVo);
        return Result.success("登录成功", loginVo);
    }

    /**
     * 用户登出
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<String> logout() {

        // 获取当前登录用户名
        if (!StpUtil.isLogin()) {
            return Result.error("用户未登录");
        }
        Result<UserInfoVo> userInfo = getUserInfo();
        String username = userInfo.getData().getUsername();
        // 执行登出操作
        StpUtil.logout();
        return Result.success("登出成功:" + username);
    }

    /**
     * 获取当前用户信息
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVo> getUserInfo() {
        if (!StpUtil.isLogin()) {
            return Result.error("用户未登录");
        }

        Integer userId = StpUtil.getLoginIdAsInt();
        User user = userService.getUserInfoById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        UserInfoVo userInfoVo = buildUserInfo(user);
        return Result.success(userInfoVo);
    }

    /**
     * 构造用户信息
     * @param user 用户实体
     * @return 用户信息VO
     */
    private UserInfoVo buildUserInfo(User user) {
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(user.getId());
        userInfoVo.setUsername(user.getUsername());
        userInfoVo.setNickname(user.getNickname());
        userInfoVo.setEmail(user.getEmail());

        // 获取用户角色
        List<Role> roles = userService.getUserRoles(user.getId());
        List<String> roleCodes = roles.stream()
                .map(Role::getCode)
                .collect(Collectors.toList());
        userInfoVo.setRoles(roleCodes);

        // 获取用户权限
        List<Permission> permissions = userService.getUserPermissions(user.getId());
        List<String> permissionCodes = permissions.stream()
                .map(Permission::getCode)
                .collect(Collectors.toList());
        userInfoVo.setPermissions(permissionCodes);

        return userInfoVo;
    }
}
